package com.linb.pan.server.common.stream.consumer.share;

import cn.hutool.core.collection.CollectionUtil;
import com.linb.pan.server.common.stream.channel.PanChannels;
import com.linb.pan.server.common.stream.event.file.DeleteFileEvent;
import com.linb.pan.server.common.stream.event.file.FileRestoreEvent;
import com.linb.pan.server.modules.file.entity.BPanUserFile;
import com.linb.pan.server.modules.file.enums.DelFlagEnum;
import com.linb.pan.server.modules.file.service.IUserFileService;
import com.linb.pan.server.modules.share.service.IShareService;
import com.linb.pan.stream.core.AbstractConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ShareStatusChangeListener extends AbstractConsumer {

    @Autowired
    private IUserFileService userFileService;

    @Autowired
    private IShareService shareService;

    /**
     * 文件被删除后，刷新所有受影响的分享的状态
     */
    @StreamListener(PanChannels.DELETE_FILE_INPUT)
    @Async(value = "eventListenerTaskExecutor")
    public void changeShare2FileDeleted(Message<DeleteFileEvent> message) {
        if (isEmptyMessage(message)) {
            return;
        }
        printLog(message);
        DeleteFileEvent event = message.getPayload();
        log.info("监听文件删除事件，刷新所有受影响的分享状态");
        //从事件中获取文件id集合
        List<Long> fileIdList = event.getFileIdList();
        if (CollectionUtil.isEmpty(fileIdList)) {
            return;
        }
        //根据文件id找出所有的文件（因为也可能包含子文件）
        List<BPanUserFile> allRecords = userFileService.findAllFileRecordsByFileIdList(fileIdList);
        //过滤脏数据，保留未删除状态的文件id集合
        List<Long> allAvailableFileIdList = allRecords.stream()
                .filter(record -> Objects.equals(DelFlagEnum.NO.getCode(), record.getDelFlag()))
                .map(BPanUserFile::getFileId)
                .collect(Collectors.toList());
        allAvailableFileIdList.addAll(fileIdList);
        //刷新状态
        shareService.refreshShareStatus(allAvailableFileIdList);
    }

    /**
     * 文件被还原后，刷新所有受影响的分享的状态
     */
    @StreamListener(PanChannels.FILE_RESTORE_INPUT)
    public void changeShare2Normal(Message<FileRestoreEvent> message) {
        if (isEmptyMessage(message)) {
            return;
        }
        printLog(message);
        FileRestoreEvent event = message.getPayload();
        log.info("监听文件还原事件，刷新所有受影响的分享状态");
        //从事件中获取文件id集合
        List<Long> fileIdList = event.getFileIdList();
        if (CollectionUtil.isEmpty(fileIdList)) {
            return;
        }
        //根据文件id找出所有的文件（因为也可能包含子文件）
        List<BPanUserFile> allRecords = userFileService.findAllFileRecordsByFileIdList(fileIdList);
        //过滤脏数据，保留未删除状态的文件id集合
        List<Long> allAvailableFileIdList = allRecords.stream()
                .filter(record -> Objects.equals(DelFlagEnum.NO.getCode(), record.getDelFlag()))
                .map(BPanUserFile::getFileId)
                .collect(Collectors.toList());
        allAvailableFileIdList.addAll(fileIdList);
        //刷新状态
        shareService.refreshShareStatus(allAvailableFileIdList);
    }

}
